//
//  DeviceController.swift
//  testapihr
//
//  Created by Tek on 2023/1/12.
//

import APIHeartRate
import IHProgressHUD
import UIKit
import DatePickerDialog
class DeviceViewController: UIViewController,
                                LoggerDelegate,
                                UICollectionViewDataSource,
                                UICollectionViewDelegate,
                            APIHeartRateObserver, APILoggerRepository {

    
    func i(tag: String, log: String) {
        Logger.log("\(tag + log)")
    }
    
    func d(tag: String, log: String) {
        Logger.log("\(tag + log)")
    }
    
    
    
    func getFinePrint(_ info: [[String : Any]]) {
        do {
            let Json = try JSONSerialization.data(withJSONObject: info , options: .prettyPrinted)
            Logger.log(String(data: Json, encoding: .utf8) ?? "")
        } catch {
            Logger.log(info.description)
        }
    }
    
    func summaryHeartRateInfo(info: [[String : Any]], isBusy: Bool) {
        if isBusy {
            Logger.log("手环繁忙，数据屏蔽中...")
            return
        }
        getFinePrint(info)
    }
    
    func summaryBloodOxygenInfo(info: [[String : Any]], isBusy: Bool) {
        if isBusy {
            Logger.log("手环繁忙，数据屏蔽中...")
            return
        }
        getFinePrint(info)
    }
    func  summaryStepsInfo(info: [[String : Any]], isBusy: Bool) {
        if isBusy {
            Logger.log("手环繁忙，数据屏蔽中...")
            return
        }
        getFinePrint(info)
    }
   
    func summaryPressureIndexInfo(info: [[String : Any]], isBusy: Bool) {
        if isBusy {
            Logger.log("手环繁忙，数据屏蔽中...")
            return
        }
       getFinePrint(info)
    }
    
    func summaryCalorieInfo(info: [[String : Any]], isBusy: Bool) {
        if isBusy {
            Logger.log("手环繁忙，数据屏蔽中...")
            return
        }
        getFinePrint(info)
    }
    
    func summarySleepInfo(info: [[String : Any]], isBusy: Bool) {
        if isBusy {
            Logger.log("手环繁忙，数据屏蔽中...")
            return
        }
        getFinePrint(info)
    }
    
    func summaryExerciseInfo(info: [[String : Any]], isBusy: Bool) {
        if isBusy {
            Logger.log("手环繁忙，数据屏蔽中...")
            return
        }
        getFinePrint(info)
    }
    
    func motionDataInfo(info: [[String : Any]], isSport: Bool, isBusy: Bool)  {
        if isBusy {
            Logger.log("手环繁忙，数据屏蔽中...")
            return
        }
        Logger.log("总条数: \(info.count)")
        getFinePrint(info)
    }
    
    func cursorInformation(info: [String : Int]) {
        getFinePrint([info])
    }
    
    func motionDataSeqUpdated(isSport: Bool) {
        
        Logger.log("\(isSport ? "运动" :"日常")历史游标已更新")
    }
    
    func currentBandTime(timeNow: Double) {
        Logger.log("当前时间: \(dateFmt.string(from: Date(timeIntervalSince1970:timeNow)))")
    }
    
    func didDiscoveryWith(discovery: [APIHeartRate.BleDicoveryDevice]) {}

    func didFinishDiscoveryWith(discovery: [APIHeartRate.BleDicoveryDevice]) {}
    func bleAvailability(status: BleAvailability) {}
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        apiManager.removeObserver(observer: self)
    }
    private var isSport = false

    deinit {
        print("de init")
    }
    
    lazy var dateFmt: DateFormatter = {
        let df = DateFormatter()
        df.dateFormat = "yyyy-MM-dd HH:mm:ss"
        df.locale = Locale.init(identifier: "en_US_POSIX")
        return df
    }()
    
    lazy var dateFmtHalf: DateFormatter = {
        let df = DateFormatter()
        df.dateFormat = "yyyy-MM-dd"
        df.locale = Locale.init(identifier: "en_US_POSIX")
        return df
    }()

    var btnArray = ["获取电量", "Manufacturer", "Model", "Hardware", "FirmWare", "Software", "SysID", "时间同步", "序列号", "实时步频", "实时血氧","充电状态","心率汇总","步数汇总","血氧汇总","压力汇总","卡路里汇总","睡眠汇总","运动汇总","日常历史","运动历史",
                    "日常模式", "运动模式", "当前模式","导出日志", "回复ACK","获取时间","模式详情","出厂设置","退出睡眠算法","切换灯光","动静态心率模式","查询心率模式", "体操模式", "一键查询","课程模式","快走模式","日常模式", "日志0", "日志1", "日志2","游标信息"]
    var apiManager = APIHeartRateManager.instance
    
    var lightOn = false
    var gymnastic = false
    var dynamicRate = false
    var mockRate = false
    
    

    lazy var mCollectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: 100, height: 50)
        layout.minimumInteritemSpacing = 10
        layout.minimumLineSpacing = 10
        let table = UICollectionView(frame: .zero, collectionViewLayout: layout)
        table.delegate = self
        table.dataSource = self
        table.contentInset = .init(top: 10, left: 10, bottom: 10, right: 10)
        table.register(BtnCell.self, forCellWithReuseIdentifier: "BTN")
        table.backgroundColor = .white
        return table
    }()

    lazy var txtFied1: UITextField = {
        let txtF = UITextField(frame: .zero)
        txtF.keyboardType = .numberPad
        txtF.placeholder = "左边界"
        txtF.borderStyle = .roundedRect
        return txtF
    }()
    lazy var txtFied2: UITextField = {
        let txtF = UITextField(frame: .zero)
        txtF.keyboardType = .numberPad
        txtF.borderStyle = .roundedRect
        txtF.placeholder = "右边界"
        return txtF
    }()
    
    lazy var txtFied3: UITextField = {
        let txtF = UITextField(frame: .zero)
        txtF.keyboardType = .numberPad
        txtF.borderStyle = .roundedRect
        txtF.placeholder = "读取条数"
        return txtF
    }()
    
    lazy var starTimeLabel: UIButton = {
        let txtF = UIButton(frame: .zero)
        txtF.setTitleColor(.black, for: .normal)
        txtF.setTitle("2023-05-02", for: .normal)
        txtF.tag = 0
        txtF.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
        return txtF
    }()
    lazy var endTimeLabel: UIButton = {
        let txtF = UIButton(frame: .zero)
        txtF.setTitleColor(.black, for: .normal)
        txtF.setTitle("2023-05-03", for: .normal)
        txtF.tag = 1
        txtF.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
        return txtF
    }()

    lazy var logTxtView: UITextView = {
        let txtView = UITextView(frame: .zero)
        txtView.isEditable = false
        txtView.alwaysBounceVertical = true
        txtView.backgroundColor = .white
        return txtView
    }()
    

    private var aliveTimer: Timer?
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        Logger.delegate = self
        apiManager.setLogger(impl: self, level: 1)
        apiManager.addObserver(observer: self)
        logTxtView.frame = CGRectMake(0, 0, view.frame.width, 300)
        mCollectionView.frame = CGRectMake(0, 310, view.frame.width, 290)
        txtFied1.frame = CGRectMake(10, 605, 100, 50)
        txtFied2.frame = CGRectMake(120, 605, 100, 50)
        starTimeLabel.frame = CGRectMake(10, 660, 200, 50)
        endTimeLabel.frame = CGRectMake(10, 710, 200, 50)
        txtFied3.frame = CGRectMake(220, 660, 140, 50)
        let sendBtn = TestBtn(frame: CGRectMake(230, 605, 80, 50), title: "设置") { [weak self] _ in
            self?.setVibrateMaxValue()
        }
        let toolbar = UIToolbar(frame: CGRectMake(0, 0, view.frame.width, 44))
        let barBtn = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(finishInputValue))
        toolbar.items = [barBtn]
        
        let disturb  = TestBtn(frame: CGRectMake(230, 710, 80, 50), title: "免打扰设置") { [weak self] _ in
            let ppv = DeviceSubViewCon()
            ppv.callBack = { [weak self]a , b , c ,d,e in
                Logger.log("设置免打扰时间:\(a)：\(b) , \(c)：\(d), 是否开启：\(e)")
                self?.apiManager.setDonotDisturbTime(enabled: e, startHour: a, startMin: b, endHour: c, endMin: d)
            }
            ppv.modalPresentationStyle = .formSheet
            self?.present(ppv, animated: true)
        }
    
        txtFied1.inputAccessoryView = toolbar
        view.addSubview(logTxtView)
        view.addSubview(mCollectionView)
        view.addSubview(txtFied1)
        view.addSubview(txtFied2)
        view.addSubview(txtFied3)
        view.addSubview(starTimeLabel)
        view.addSubview(endTimeLabel)
        view.addSubview(sendBtn)
        view.addSubview(disturb)
        
        let s1 = Date()
        starTimeLabel.setTitle(dateFmtHalf.string(from: s1.addingTimeInterval(-24 * 60 * 60)), for: .normal)
        endTimeLabel.setTitle(dateFmtHalf.string(from: s1), for: .normal)
        
        apiManager.requestCurrentTime()
        
        
        
    }
    
    
    lazy var datePicker: UIDatePicker = {
        let picker = UIDatePicker(frame: .zero)
        picker.locale = Locale.current
        return picker
    }()
    func showDatePicker() {
        datePicker.frame = CGRectMake(view.frame.width / 2, view.frame.height / 2, 300, 300)
        view.addSubview(datePicker)
    }
    
    @objc
    func updateSync() {
        apiManager.updateSeq(sportMode: isSport)
    }
    
    @objc
    func btnClick(sender: UIButton) {
        if (sender.tag == 0) {
            let sStr =  starTimeLabel.title(for: .normal) ?? "2023-05-01"
            let d1 = dateFmt.date(from: sStr) ?? Date()
            DatePickerDialog(locale:Locale.current).show("开始时间", doneButtonTitle: "确定", cancelButtonTitle: "取消", defaultDate: d1, datePickerMode: .date) { date in
                    if let dt = date {
                        self.starTimeLabel.setTitle(self.dateFmtHalf.string(from: dt), for: .normal)
                    }
                }
        }
        else {
            let eStr =  endTimeLabel.title(for: .normal) ?? "2023-05-02"
            let d2 = dateFmt.date(from: eStr) ?? Date()
            DatePickerDialog(locale:Locale.current).show("结束时间", doneButtonTitle: "确定", cancelButtonTitle: "取消",defaultDate: d2, datePickerMode: .date) { date in
                    if let dt = date {
                        self.endTimeLabel.setTitle(self.dateFmtHalf.string(from: dt), for: .normal)
                    }
                }
        }
    }
    
    @objc
    func finishInputValue() {
        txtFied1.resignFirstResponder()
    }

    func fireMyTimer(stop: Bool) {
        if (aliveTimer == nil) {
            aliveTimer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(sendingSignal), userInfo: nil, repeats: true)
        }
        if (stop) {
            aliveTimer?.invalidate()
            aliveTimer = nil
        } else {
            aliveTimer?.fire()
        }
        
    }
    
    @objc
    func sendingSignal() {
        Logger.log("开始发送运动心跳=====")
        apiManager.keepSportAlive()
        
    }
    
    
    func loggerDidLogString(_ string: String) {
        if logTxtView.text.count > 0 {
            logTxtView.text = logTxtView.text + ("\n" + string)
        } else {
            logTxtView.text = string
        }
        logTxtView.scrollRangeToVisible(NSRange(location: logTxtView.text.count - 1, length: 1))
    }

    func setVibrateMaxValue() {
        guard let v = txtFied1.text , let v2 = txtFied2.text else {
            Logger.log("阈值输入有误")
            return
        }
        apiManager.setHeartRateThreshold(min: UInt8(v) ?? 0, max: UInt8(v2) ?? 0)
    }

    // MARK: Collection View

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return btnArray.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BTN", for: indexPath) as? BtnCell {
            cell.setTxt(txt: btnArray[indexPath.item])
            return cell
        }
        return UICollectionViewCell()
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        Logger.log("开始 \(btnArray[indexPath.item]):")
        switch indexPath.item {
        case 0:
            apiManager.readDeviceBatteryPower()
        case 1:
            apiManager.getManufacturerName()
        case 2:
            apiManager.getModelName()
        case 3:
            apiManager.getHardwareVersion()
        case 4:
            apiManager.getFirmwareVersion()
        case 5:
            apiManager.getSoftwareVersion()
        case 6:
            apiManager.getSystemID()
        case 7:
            apiManager.syncDeviceTime()
        case 8:
            apiManager.getSerialNum()
        case 9:
            apiManager.getStepFrequency()
        case 10:
            apiManager.getRTOxygen()
        case 11:
            apiManager.queryBatteryStatus()
        case 12, 13, 14, 15, 16, 17 ,18:
            requireByType(type: indexPath.item)
        case 19:
            isSport = false
            apiManager.getMotionData(pageSize: Int(txtFied3.text ?? "1") ?? 1, sportMode: false)
        case 20:
            isSport = true
            apiManager.getMotionData(pageSize: Int(txtFied3.text ?? "60") ?? 60, sportMode: true)
        case 21:
            apiManager.switchDeviceMode(mode: .daily, isReal: false)
        case 22:
            mockRate = !mockRate
            apiManager.switchDeviceMode(mode: .sport, isReal: mockRate)
        case 23:
            apiManager.queryDeviceMode()
        case 24:
            exportLogs()
        case 25:
            updateSync()
        case 26:
            apiManager.requestCurrentTime()
        case 27:
            apiManager.qureySportModeDetail()
        case 28:
            apiManager.resetBand()
        case 29:
            apiManager.forseSleepOut()
        case 30:
            apiManager.lightSwitch(on: lightOn)
            lightOn = !lightOn
        case 31:
            apiManager.dynamicHeartRate(on: dynamicRate)
            dynamicRate = !dynamicRate
        case 32:
            apiManager.queryHeartRateMode()
        case 33:
            apiManager.gymnasticMode(on: gymnastic)
            gymnastic = !gymnastic
        case 34:
            apiManager.queryDeviceInformation()
        case 35:
            apiManager.switchScenario(type: .lesson)
        case 36:
            apiManager.switchScenario(type: .quickWalk)
        case 37:
            apiManager.switchScenario(type: .daily)
        case 38:
            apiManager.setLoggerLevel(level: 0)
        case 39:
            apiManager.setLoggerLevel(level: 1)
        case 40:
            apiManager.setLoggerLevel(level: 2)
        case 41:
            apiManager.queryCursorInfo()
        default:
            break
        }
    }

    private func CheckCreateDirectory(path pathdirectory:String) -> Bool{
        let filemanager = FileManager.default
        if !filemanager.fileExists(atPath: pathdirectory) {
            do {
                try filemanager.createDirectory(atPath: pathdirectory, withIntermediateDirectories: true, attributes: nil)
            } catch {
                print("Error creating directory \(pathdirectory) : \(error.localizedDescription)")
                return false
            }
        }
        return true
    }
    
    private func Write(data strData:String, tofile path:String) -> Bool{
        do {
            try strData.write(toFile: path, atomically: true, encoding: .utf8)
        } catch {
            print("Error write file \(path) : \(error.localizedDescription)")
            return false
        }
        return true
    }
    
    
    func exportLogs() {
        
        IHProgressHUD.show()
        var CachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0]
        CachePath = "\(CachePath)/tmptxt"
        let _ = self.CheckCreateDirectory(path: CachePath)
        
        let FolderId = "folderxls\(arc4random())"
        let BasePath = "\(CachePath)/\(FolderId)"
        let _ = self.CheckCreateDirectory(path: BasePath)
        let pat = "\(BasePath)/sample\(arc4random()).txt"
        let _ = Write(data: logTxtView.text, tofile:pat)
        let fileUrl = NSURL(fileURLWithPath: pat)
        let shareV = UIActivityViewController(activityItems: [fileUrl], applicationActivities: nil)
        present(shareV, animated: true)
        IHProgressHUD.dismiss()

    }

    private func RemoveFile(path pathfile: String) -> Bool {
        do {
            try FileManager.default.removeItem(atPath: pathfile)
        } catch {
            print("Error remove file \(pathfile) : \(error.localizedDescription)")
            return false
        }
        return true
    }

    func requireByType(type: Int) {
        let sStr =  starTimeLabel.title(for: .normal) ?? "2023-05-01"
        let eStr =  endTimeLabel.title(for: .normal) ?? "2023-05-02"
        let d1 = dateFmtHalf.date(from: sStr)?.timeIntervalSince1970
        let d2 = dateFmtHalf.date(from: eStr)?.timeIntervalSince1970
        
        switch(type) {
        case 12:
            apiManager.getSummaryHeartRate(startDateStamp: d1?.rounded() ?? 0, endDateStamp: d2?.rounded() ?? 0)
        case 13:
            apiManager.getSummarySteps(startDateStamp: d1?.rounded() ?? 0, endDateStamp: d2?.rounded() ?? 0)
        case 14:
            apiManager.getSummaryBloodOxygen(startDateStamp: d1?.rounded() ?? 0, endDateStamp: d2?.rounded() ?? 0)
        case 15:
            apiManager.getSummaryPressureIndex(startDateStamp: d1?.rounded() ?? 0, endDateStamp: d2?.rounded() ?? 0)
        case 16:
            apiManager.getSummaryCalorie(startDateStamp: d1?.rounded() ?? 0, endDateStamp: d2?.rounded() ?? 0)
        case 17:
            apiManager.getSummarySleep(startDateStamp: d1?.rounded() ?? 0, endDateStamp: d2?.rounded() ?? 0)
        case 18:
            apiManager.getExerciseData(startDateStamp: d1?.rounded() ?? 0, endDateStamp: d2?.rounded() ?? 0)
        default:
            break
        }
    }
    func showAlert() {
        let alertCon = UIAlertController(title: "提示", message: "手环已已断开", preferredStyle: .alert)
        alertCon.addAction(UIAlertAction(title: "好的", style: .default) { [weak self] _ in
            //self?.navigationController?.popViewController(animated: true)
        })
        present(alertCon, animated: true)
    }

    // MARK: API Delegate

    func bleConnectError(error: APIHeartRate.BleConnectError, device: APIHeartRate.BleDevice?) {
        var e = ""
        switch error {
        case .deviceNotConnected:
            e = "设备未连接"
            break
        case .deviceNotFound:
            e = "未找到设备"
            break
        case .scanFailed:
            e = "扫描失败"
            break
        case let .failedToDisconnect(underlineError):
            e = "断连失败：" + (underlineError?.localizedDescription ?? "")
            break
        case .failedToConnectDueToTimeout:
            e = "连接超时"
            break
        default:
            e = "未知错误"
            break
        }
        IHProgressHUD.showError(withStatus: e)
        Logger.log(e)
    }

    func bleCommonError(error: APIHeartRate.BleCommonError) {
        var logS = ""
        switch error {
        case .devieNotConnected:
            logS = "设备未连接"
            break
        case .deviceNotFound:
            logS = "未找到设备"
            break
        case .serviceNotFound:
            logS = "未找到该服务"
            break
        case .receivedWrongData:
            logS = "收到错误数据"
            break
        default:
            logS = "发生未知错误"
            break
        }
        Logger.log(logS)
    }

    func bleConnectStatus(status: APIHeartRate.DeviceBleStatus, device: APIHeartRate.BleDevice?) {
        switch status {
        case .disconnected:
            showAlert()
            break
        default:
            break
        }
    }

    func devicePower(power: String, device: APIHeartRate.BleDevice) {
        Logger.log("电量为： \(power)")
    }

    func bleConnectLog(logString: String, device: APIHeartRate.BleDevice?) {
        Logger.log(logString)
    }

    func privateVersion(version: [String: String], device: APIHeartRate.BleDevice) {
        Logger.log("私有版本为： \(version)")
    }

    func privateMacAddress(mac: String, device: APIHeartRate.BleDevice) {
        Logger.log("Mac地址为： \(mac)")
    }

    func deviceSystemData(systemData: Data, device: APIHeartRate.BleDevice) {
        Logger.log("系统ID为： \(systemData)")
    }

    func deviceFirmware(version: String, device: APIHeartRate.BleDevice) {
        Logger.log("固件版本： \(version)")
    }

    func deviceHardware(version: String, device: APIHeartRate.BleDevice) {
        Logger.log("硬件版本： \(version)")
    }

    func deviceSoftware(version: String, device: APIHeartRate.BleDevice) {
        Logger.log("软件版本： \(version)")
    }

    func deviceModelString(modelString: String, device: APIHeartRate.BleDevice) {
        Logger.log("moodel为： \(modelString)")
    }

    func deviceSerialNumber(serialNumer: String, device: APIHeartRate.BleDevice) {
        Logger.log("serial为： \(serialNumer)")
    }
    
    func deviceManufacturerName(manufacturerName: String, device: APIHeartRate.BleDevice) {
        Logger.log("Manufacture为： \(manufacturerName)")
    }
    func exitedSleepAlgorithm() {
        Logger.log("退出了睡眠算法")
    }
    
    func gymnasticModeChanged(on: Bool) {
        Logger.log("体操模式:\(on ? "进入" : "退出")")
    }
    func rawDataLog(type: FetchDataType, log: String) {
        Logger.log("原始数据\(type): \(log)")
    
    }
    func inForceDynamicMode() {
        Logger.log("当前是强制心率模式")
    }
    func heartRateMockStatus(on: Bool) {
        Logger.log("模拟心率:\(on ? "开" : "关")")
    }
    func wearingStatus(status: WearStatus) {
        Logger.log("佩戴模式：\(status == .loosen ? "松" : "超时")")
    }
    
    func deviceInformation(info: [String : Any]) {
//        let on = info["doNotDisturbOn"] as! Bool
//        Logger.log("勿扰模式:\(on ? "开" : "关")，时段：\(info["startHour"] as! Int):\(info["startMin"] as! Int) -- \(info["endHour"] as! Int):\(info["endMin"] as! Int)")
        Logger.log(info.description)
    }
    
    func scenarioChanged(type: ScenarioType) {
        var typeStr = ""
        switch(type) {
        case .lesson:
            typeStr = "课程模式"
        case .quickWalk:
            typeStr = "快走模式"
        case .daily:
            typeStr = "日常模式"
        default:
            break
        }
        Logger.log("当前模式：\(typeStr)")
    }
    
    func heartRateModeChange(mode: HeartRateMode) {
        var str = ""
        switch (mode) {
        case .autoDynamic:
            str = "自动动态"
        case .autoStatic:
            str = "自动静态"
        case .forceDynamic:
            str = "强制动态"
        @unknown default:
           break
        }
        Logger.log("心率模式: \(str)")
    }
    
    private let current =  ["日常模式","运动模式"]
    private let source =  ["自动进入","app进入"]
    private let sportLevel =  ["日常","轻度运动", "重度运动"]
    
    func sportModeDetailInfo(info: [String : Int], isBusy: Bool) {
        
        if isBusy {
            Logger.log("手环繁忙，数据屏蔽中...")
            return
        }
        
        let ax = info["current"] ?? 0
        let _ = info["current"] ?? 0
        let ax2 = info["current"] ?? 0
        var ret:[String: Any] = [:]
        ret["当前模式"] =  current[ax]
        ret["类型"] =  source[ax2]
        ret["运动等级"] =  sportLevel[ax2]
        ret["日常累计"] =  info["daily"] ?? 0
        ret["轻度累计"] =  info["low"] ?? 0
        ret["重度累计"] =  info["heavy"] ?? 0
        ret["当前心率"] =  info["daily"] ?? 0
        ret["运动区间1"] =  info["sp1"] ?? 0
        ret["运动区间2"] =  info["sp2"] ?? 0
        ret["运动区间3"] =  info["sp3"] ?? 0
        ret["日常区间1"] =  info["dl1"] ?? 0
        ret["日常区间2"] =  info["dl2"] ?? 0
        ret["日常区间3"] =  info["dl3"] ?? 0
        getFinePrint([ret])
    }
    
    func armBandModeChanged(mode: DeviceMode, type: ModeType) {
        var str = "其他"
        switch (type) {
        case .autoIn:
            str = "自动进入"
        case .autoOut:
            str = "自动进入"
        default:
            str = "其他"
        }
        Logger.log("当前模式:\(mode == .daily ? "日常" : "运动")模式，类型：\(str)")
        fireMyTimer(stop: mode == .daily)
        
    }
    
    func armBandRealTimePressure(pressure: Int, device: BleDevice) {
        Logger.log("当前压力值为：\(pressure)")
    }

    func armBandMaxHeartRateUpdated() {
        Logger.log("阈值更新成功")
    }

    func armBandSystemTimeUpdated() {
        Logger.log("系统时间同步成功")
    }

    func armBandRealTimeHeartRate(hRInfo: APIHeartRate.HRInfo, device: APIHeartRate.BleDevice) {
        Logger.log("心率为： \(hRInfo.rateStr)")
    }

    func armBandResetFactory(isTimeOut: Bool) {
        Logger.log("恢复出厂 是否超时: \(isTimeOut)")
    }
    func armBandPlayStatusChange() {
        Logger.log("切换播放状态")
    }

    func armBandUnbind() {
        Logger.log("解除绑定")
    }
    
    func batteryStatus(state: BatteryStatus) {
        Logger.log("状态：\(state)")
    }
    
    func heartRateInMeasuring() {
        Logger.log("心率测量中")
    }
    
    func lightStatusChanged(on: Bool) {
        Logger.log("灯光切换:\(on)")
    }
    
    func dynamicRateChanged(on: Bool) {
        Logger.log("动态心率:\(on ? "进入" : "退出")")
    }

    func deviceBaseInfo(baseInfo: APIHeartRate.FBKApiBaseInfo, device: APIHeartRate.BleDevice) { }

    func HRVResultData(hrvMap: [String: String], device: APIHeartRate.BleDevice) {}

    func armBandStepFrequency(frequencyDic: [String: String], device: APIHeartRate.BleDevice) {
        Logger.log("实时步频：\(String(describing: frequencyDic["value"]))")
    }

    func armBandTemperature(tempMap: [String: String], device: APIHeartRate.BleDevice) {}

    func armBandSPO2(spo2Map: [String: String], device: APIHeartRate.BleDevice) {}
    func armBandBloodOxygen(num: Int, device: APIHeartRate.BleDevice) {
        Logger.log("实时血氧：\(num)")
    }
    
    func doNotDisturbTimeInfo(enabled: Bool, startHour: UInt8, startMin: UInt8, endHour: UInt8, endMin: UInt8) {
        Logger.log("免打扰设置成功")
//        Logger.log("免打扰时间ACK:\(startHour):\(startMin) , \(endHour):\(endMin), 是否开启：\(enabled)")
    }
    
}
